<?php

namespace App\Models\Admin;

use Illuminate\Database\Eloquent\Model;

class AdManage extends Model{
    protected $table = 'ad_manage';
    protected $primaryKey = 'id';
    protected $guarded = [];

    /**
     * 返回广告链接
     * @param $value
     */
    public function setAdUrlAttribute($value){
        switch($this->url_type){
            case 1 :
                $this->attributes['ad_url'] = (strstr($this->url, 'https') || strstr($this->url, 'http')) ? $this->url : 'http://' . $this->url;
                break;
            case 2 :
                $this->attributes['ad_url'] = asset('comabout_' . idEncryption($this->url) . '.html');
                break;
            case 3 :
                $this->attributes['ad_url'] = asset('jobinfo_' . idEncryption($this->url) . '.html');
                break;
        }
    }

    /*@param
     * $site 广告位站点标识
     * $slots 广告位位置标识
     */
    static public function getAd($site, $slots){
        $ad_site = AdSite::where('site_sign', $site)->first(['id']);
        $ad_slots = AdSlots::where('ad_sign', $slots)->first(['id', 'ad_number', 'width', 'height']);
        if($ad_site && $ad_slots){
            $adManage = AdManage::where('ad_site', $ad_site->id)->where('ad_slots', $ad_slots->id)
                ->select('id', 'com_id', 'title', 'url_type', 'url', 'pic_url', 'width', 'height')
                ->where('status', '1')
                ->take($ad_slots->ad_number)
                ->orderBy('sort', 'asc')
                ->get();

            foreach($adManage as $v){
                $v->ad_url = $v->url;
                $v->pic_url = asset('upload/adminad/' . $v->pic_url);
                $v->width = !empty($v->width) ? $v->width : $ad_slots->width;
                $v->height = !empty($v->height) ? $v->height : $ad_slots->height;
            }
            return $adManage;
        }else{
            return array();
        }
    }
}
